package com.rjj.wlqq.tool.io;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author renjianjun
 * @date 2020/9/7 11:22
 * @email 215060580@qq.com
 * <p>
 * @link [https://segmentfault.com/a/1190000023601065]
 *
 *  空格变为加号问题解决
 */
@Slf4j
public class Download {

    public static String download(String serverFileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        String clientFileName = serverFileName.substring(serverFileName.lastIndexOf("/") + 1);
        log.info("文件名称：{}", clientFileName);
        // 对真实文件名进行百分号编码
        String percentEncodedFileName = URLEncoder.encode(clientFileName, "utf-8")
                .replaceAll("\\+", "%20");
        // 组装contentDisposition的值
        String contentDispositionValue = "attachment; filename=" +
                percentEncodedFileName + ";" +
                "filename*=" + "utf-8''" +
                percentEncodedFileName;
        response.setHeader("Content-disposition", contentDispositionValue);
        // 将文件流写到response中
        try (InputStream inputStream = new FileInputStream(serverFileName);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
             OutputStream outputStream = response.getOutputStream();
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
        ) {
            IOUtils.copy(bufferedInputStream, bufferedOutputStream);
        }
        return "OK!";
    }
}
